import { z } from "zod"
import { createSuccessResponse } from "../utils/response"
import { router, publicProcedure } from "./trpc"
import { authRouter } from "./routers/auth"
import { adminRouter } from "./routers/admin"
import { userRouter } from "./routers/user"
import { rechargeRouter } from "./routers/recharge"
import { payoutRouter } from "./routers/payout"
import { channelConfigRouter } from "./routers/channelConfig"
import { createRechargeSession } from "../utils/sessionManager"

// 健康检查路由
const healthRouter = router({
  check: publicProcedure.query(() => {
    return createSuccessResponse(
      {
        status: "ok",
        timestamp: new Date().toISOString(),
        service: "vue-turbo-stack-api",
        version: "1.0.0",
        uptime: process.uptime(),
      },
      "服务运行正常"
    )
  }),
})

// 在文件顶部添加存储结构 - 按saasId分组存储数据数组
const storedDataMap = new Map<string, Array<{ appid: string; saasId: string; usename: string }>>()

// echoRouter - 创建充值会话并返回充值页面URL
const echoRouter = router({
  echo: publicProcedure
    .input(
      z.object({
        appid: z.string(),
        saasId: z.string(),
        usename: z.string(),
      })
    )
    .mutation(({ input }) => {
      // 获取或创建对应saasId的数组（保持原有功能）
      const existingData = storedDataMap.get(input.saasId) || []
      existingData.push(input)
      storedDataMap.set(input.saasId, existingData)

      console.log(`Stored data for saasId ${input.saasId}:`, input)
      
      // 创建充值会话并生成URL
      const sessionResult = createRechargeSession({
        appid: input.appid,
        saasId: input.saasId,
        username: input.usename
      })

      console.log(`Created recharge session ${sessionResult.sessionId} for user ${sessionResult.extractedUserId}`)

      // 返回URL和相关信息
      return createSuccessResponse({
        rechargeUrl: sessionResult.url,
        sessionId: sessionResult.sessionId,
        extractedUserId: sessionResult.extractedUserId,
        originalData: storedDataMap.get(input.saasId) || []
      }, "Recharge session created successfully")
    }),
})


// 主路由
export const appRouter = router({
  health: healthRouter,
  echo: echoRouter,
  auth: authRouter,
  admin: adminRouter,
  user: userRouter,
  recharge: rechargeRouter,
  payout: payoutRouter,
  channelConfig: channelConfigRouter,
})

export type AppRouter = typeof appRouter
